<template>
  <div class="article-edit-container">
    <el-card class="article-edit-card" :body-style="{ padding: '20px' }">
      <div class="card-header">
        <h1>{{ isEdit ? '编辑文章' : '创建新文章' }}</h1>
      </div>
      
      <el-form :model="articleForm" :rules="rules" ref="articleForm" label-width="80px" class="article-form">
        <el-form-item label="标题" prop="title">
          <el-input 
            v-model="articleForm.title" 
            placeholder="请输入文章标题"
            class="title-input"
            :maxlength="100"
            show-word-limit
          ></el-input>
        </el-form-item>
        
        <el-form-item label="内容" prop="content">
          <el-input 
            type="textarea" 
            v-model="articleForm.content" 
            placeholder="请输入文章内容"
            :rows="15"
            class="content-input"
            resize="none"
          ></el-input>
        </el-form-item>
        
        <el-form-item class="form-buttons">
          <el-button 
            type="primary" 
            @click="submitForm" 
            :loading="loading"
            class="submit-button"
          >
            {{ isEdit ? '保存修改' : '发布文章' }}
          </el-button>
          <el-button @click="cancel" class="cancel-button">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'ArticleEdit',
  data() {
    return {
      articleForm: {
        title: '',
        content: '',
        userId: null
      },
      rules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 2, max: 100, message: '标题长度在2到100个字符之间', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入文章内容', trigger: 'blur' },
          { min: 10, message: '内容至少10个字符', trigger: 'blur' }
        ]
      },
      loading: false,
      isEdit: false,
      articleId: null
    }
  },
  created() {
    // 检查是否有用户登录
    const userInfo = localStorage.getItem('userInfo');
    if (!userInfo) {
      this.$message.error('请先登录');
      this.$router.push('/login');
      return;
    }
    
    const user = JSON.parse(userInfo);
    this.articleForm.userId = user.id;
    
    // 判断是编辑还是创建
    this.articleId = this.$route.params.id;
    this.isEdit = !!this.articleId;
    
    if (this.isEdit) {
      this.fetchArticleData();
    }
  },
  methods: {
    fetchArticleData() {
      this.$axios.get(`/api/posts/${this.articleId}`)
        .then(response => {
          const article = response.data;
          this.articleForm.title = article.title;
          this.articleForm.content = article.content;
        })
        .catch(error => {
          console.error('获取文章数据失败:', error);
          this.$message.error('获取文章数据失败，请稍后重试');
        });
    },
    submitForm() {
      this.$refs.articleForm.validate(valid => {
        if (!valid) {
          return false;
        }
        
        this.loading = true;
        
        if (this.isEdit) {
          // 更新文章
          this.$axios.put(`/api/posts/${this.articleId}`, this.articleForm)
            .then(response => {
              this.$message.success('文章更新成功');
              this.loading = false;
              this.$router.push(`/posts/${this.articleId}`);
            })
            .catch(error => {
              console.error('更新文章失败:', error);
              this.$message.error('更新文章失败，请稍后重试');
              this.loading = false;
            });
        } else {
          // 创建新文章
          this.$axios.post('/api/posts', this.articleForm)
            .then(response => {
              this.$message.success('文章发布成功');
              this.loading = false;
              this.$router.push(`/posts/${response.data.id}`);
            })
            .catch(error => {
              console.error('发布文章失败:', error);
              let errorMessage = error.response?.data?.message;
              
              if (!errorMessage) {
                if (error.code === 'ECONNABORTED') {
                  errorMessage = '请求超时，请检查网络连接后重试';
                } else if (error.message.includes('Network Error')) {
                  errorMessage = '网络连接失败，请检查网络设置';
                } else {
                  errorMessage = '服务器连接异常，请检查网络后重试';
                }
              }
              
              const statusMessages = {
                400: '请求参数错误，请检查输入内容',
                401: '登录已过期，请重新登录',
                403: '没有操作权限',
                500: '服务器内部错误',
                502: '网关错误，服务器暂时不可用',
                503: '服务不可用，请稍后重试',
                504: '网关超时，请稍后重试'
              };
              this.$message.error(statusMessages[error.response?.status] || errorMessage);
              this.loading = false;
            });
        }
      });
    },
    cancel() {
      this.$router.go(-1);
    },
    
    testNetworkConnection() {
      this.loading = true;
      this.$axios.get('/api/health')
        .then(() => {
          this.$message.success('网络连接正常');
          this.loading = false;
        })
        .catch(error => {
          let errorMessage = '网络连接失败';
          if (error.code === 'ECONNABORTED') {
            errorMessage = '请求超时，请检查网络连接';
          } else if (error.message.includes('Network Error')) {
            errorMessage = '无法连接到服务器，请检查网络设置';
          } else if (error.response?.status === 404) {
            errorMessage = '服务器端点不存在，请联系管理员';
          }
          this.$message.error(errorMessage);
          this.loading = false;
        });
    }
  }
}
</script>

<style scoped>
.article-edit-container {
  max-width: 900px;
  margin: 20px auto;
  padding: 0 20px;
}

.article-edit-card {
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.post-edit-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
}

.card-header {
  text-align: center;
  margin-bottom: 30px;
}

h1 {
  font-size: 24px;
  color: #2c3e50;
  margin: 0;
  font-weight: 600;
}

.article-form {
  margin-top: 20px;
}

.title-input :deep(.el-input__wrapper) {
  border-radius: 6px;
}

.content-input :deep(.el-textarea__inner) {
  border-radius: 6px;
  padding: 12px;
  line-height: 1.6;
  font-size: 15px;
}

.form-buttons {
  margin-top: 30px;
  text-align: center;
}

.submit-button {
  min-width: 120px;
  border-radius: 6px;
  font-weight: 500;
}

.cancel-button {
  min-width: 100px;
  border-radius: 6px;
}

@media (max-width: 768px) {
  .article-edit-container {
    padding: 0 10px;
    margin: 10px auto;
  }
  
  .article-edit-card {
    border-radius: 0;
  }
  
  h1 {
    font-size: 20px;
  }
  
  .el-form-item {
    margin-bottom: 15px;
  }
}
</style>